#!/bin/bash

# if error, exit immediately
set -e

# config params
# builder work dir
WORK_DIR=$(cd "$(dirname "$0")" && pwd -P)
echo "builder work dir: ${WORK_DIR}"
# target directory
TARGET_DIR=$(dirname "$(pwd)")
echo "builder target dir: ${TARGET_DIR}"
# RootFS directory:Compile environment
ROOTFS_DIR="${TARGET_DIR}/sys_rootfs"
# rootfs boot directory
ROOTFS_BOOT_DIR="${ROOTFS_DIR}/boot"
# sys_boot dir:vmlinuz、initrd.img、grub.cfg...
SYS_BOOT_DIR="${TARGET_DIR}/sys_boot"
# pool directory:system packages
POOL_DIR="${TARGET_DIR}/pool"
# CPU architecture:ARCH="amd64"、ARCH="arm64"
ARCH="amd64"
# Debian kernel version
KERNEL_VERSION="6.1.0-35-${ARCH}"
# SysBoot version
SYS_BOOT_VERSION="1.0.0-${ARCH}"
# SysBoot name
SYS_BOOT_NAMR="SysBoot-${SYS_BOOT_VERSION}.tar.gz"

# publish system boot files
# clean system boot files
if [ ! -d ${SYS_BOOT_DIR} ]; then
    mkdir -p ${SYS_BOOT_DIR}
fi

# clean pool dir
if [ ! -d ${POOL_DIR} ]; then
    mkdir -p ${POOL_DIR}
fi

# publish kernel:vmlinuz
# clean old vmlinuz
if [ -f ${SYS_BOOT_DIR}/vmlinuz-${KERNEL_VERSION} ]; then
    rm -f ${SYS_BOOT_DIR}/vmlinuz-${KERNEL_VERSION}
fi
# copy vmlinuz
cp ${ROOTFS_BOOT_DIR}/vmlinuz-${KERNEL_VERSION} ${SYS_BOOT_DIR}/vmlinuz-${KERNEL_VERSION}

# publish initrd.img
# clean old initrd.img
if [ -f ${SYS_BOOT_DIR}/initrd.img-${KERNEL_VERSION} ]; then
    rm -f ${SYS_BOOT_DIR}/initrd.img-${KERNEL_VERSION}
fi
# copy initrd.img
cp ${ROOTFS_BOOT_DIR}/initrd.img-${KERNEL_VERSION} ${SYS_BOOT_DIR}/initrd.img-${KERNEL_VERSION}

# publish config
# clean old config
if [ -f ${SYS_BOOT_DIR}/config-${KERNEL_VERSION} ]; then
    rm -f ${SYS_BOOT_DIR}/config-${KERNEL_VERSION}
fi
# copy config
cp ${ROOTFS_BOOT_DIR}/config-${KERNEL_VERSION} ${SYS_BOOT_DIR}/config-${KERNEL_VERSION}

# publish System.map
# clean old System.map
if [ -f ${SYS_BOOT_DIR}/System.map-${KERNEL_VERSION} ]; then
    rm -f ${SYS_BOOT_DIR}/System.map-${KERNEL_VERSION}
fi
# copy System.map
cp ${ROOTFS_BOOT_DIR}/System.map-${KERNEL_VERSION} ${SYS_BOOT_DIR}/System.map-${KERNEL_VERSION}

# cd to work dir
cd ${WORK_DIR}
# copy grub config
if [ ! -d ${ROOTFS_BOOT_DIR}/grub ]; then
    mkdir -p ${ROOTFS_BOOT_DIR}/grub
fi
if [ -f ${ROOTFS_BOOT_DIR}/grub/grub.cfg ]; then
    rm -f ${ROOTFS_BOOT_DIR}/grub/grub.cfg
fi
cp -f ${WORK_DIR}/grub/grub_uefi.cfg ${ROOTFS_BOOT_DIR}/grub/grub.cfg
if [ ! -d ${SYS_BOOT_DIR}/grub ]; then
    mkdir -p ${SYS_BOOT_DIR}/grub
fi
if [ -f ${SYS_BOOT_DIR}/grub/grub.cfg ]; then
    rm -f ${SYS_BOOT_DIR}/grub/grub.cfg
fi
cp -f ${ROOTFS_BOOT_DIR}/grub/grub.cfg ${SYS_BOOT_DIR}/grub/grub.cfg

# publish SysBoot
# clean old SysBoot
if [ -f ${POOL_DIR}/${SYS_BOOT_NAMR} ]; then
    echo "Remove old ${SYS_BOOT_NAMR} ..."
    rm -f ${POOL_DIR}/${SYS_BOOT_NAMR}   
fi
echo "Package ${SYS_BOOT_NAMR} ..."
# package SysBoot edisk
cd ${SYS_BOOT_DIR}
tar -czf ${POOL_DIR}/${SYS_BOOT_NAMR} .
echo "Package ${SYS_BOOT_NAMR} is created at ${POOL_DIR}/${SYS_BOOT_NAMR}"
